package me.iholo.dao.impl;

import me.iholo.dao.BaseDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;

/**
 * Created by iholome on 2017/6/16 0016.
 */
@Repository
@Transactional
public abstract class BaseDaoImpl<K extends Serializable, T extends Serializable> implements BaseDao<K, T> {
    @Autowired
    private SessionFactory sessionFactory;
    private Class<T> tClass;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public BaseDaoImpl(Class<T> tClass) {
        this.tClass = tClass;
    }



    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public K save(T t) {
        Session session=getSession();

        return (K)session.save(t);
    }

    public void saveAll(Collection<T> collection) {
            Session session=getSession();
            for(T t: collection){
                session.save(t);
            }
    }

    public T findById(K id) {
        Session session=getSession();
        T t=session.get(tClass,id);
        return t;
    }

    public T update(T t) {
        Session session=getSession();
        session.update(t);
        return t;
    }

    public T saveOrUpdate(T t) {
        Session session=getSession();
        session.saveOrUpdate(t);
        return t;
    }

    public void delete(T t) {
        Session session=getSession();
        session.delete(t);
    }

    public void deleteAll(Collection<T> collection) {
        Session session=getSession();
        for (T t: collection){
            session.delete(t);
        }
    }

    public boolean deleteById(K id) {
        Session session=getSession();
        T t=session.find(tClass,id);
        if(t==null)
            return false;
        session.delete(t);
        return true;

    }
}
